<template>
  <div class="invoiceDetail">
    <div class="pageheader">
      <XHeader :left-options="{backText:''}" title="发票详情" class="XHeader"></XHeader>
    </div>

    <div>
      <flow>
        <flow-state :title="'订单下单'" :is-done="orderActive === 2 || orderActive === 3"></flow-state>
        <flow-line :is-done="orderActive === 2 || orderActive === 3"
                   :process-span="orderActive === 1 ? 50 : 100"></flow-line>
        <flow-state :title="'订单完成'" :is-done="orderActive === 3 || orderActive === 2"></flow-state>
        <flow-line :is-done="orderActive === 3 || orderActive === 2"
                   :process-span="orderActive === 2 ? 50 : 100"></flow-line>
        <flow-state :title="'商家开票'" :is-done="orderActive === 3"></flow-state>
      </flow>
    </div>

    <!--发票状态-->
    <div class="invoiceDetail-con">
      <div class="invoiceDetail-con-list">
        <div class="invoiceDetail-con-list-tit">开票状态：</div>
        <div class="invoiceDetail-con-list-val invoiceDetail-tip">{{invoiceStatus}}</div>
      </div>
    </div>

    <!--订单信息-->
    <div class="invoiceDetail-con">
      <div class="invoiceDetail-title">订单信息</div>
      <div class="invoiceDetail-con-list" v-for="(item, index) in orderList" :key="index">
        <div class="invoiceDetail-con-list-tit">{{item.name}}：</div>
        <div class="invoiceDetail-con-list-val">{{item.value}}</div>
      </div>
    </div>

    <!--发票信息-->
    <div class="invoiceDetail-con" v-if="invoiceList.length">
      <div class="invoiceDetail-title">开票信息</div>
      <div class="invoiceDetail-con-list" v-for="(item, index) in invoiceList" :key="index">
        <div class="invoiceDetail-con-list-tit">{{item.name}}：</div>
        <div class="invoiceDetail-con-list-val" :class="[item.isRed ? 'invoiceDetail-tip' : null]">{{item.value}}</div>
      </div>
    </div>

    <!--收票信息-->
    <div class="invoiceDetail-con" v-if="perList[0] && perList[0].value">
      <div class="invoiceDetail-title">联系信息</div>
      <div class="invoiceDetail-con-list" v-for="(item, index) in perList" :key="index">
        <div class="invoiceDetail-con-list-tit">{{item.name}}：</div>
        <div class="invoiceDetail-con-list-val">{{item.value}}</div>
      </div>
    </div>

    <!--发票列表-->
    <div class="invoiceDetail-con invoiceDetail-info" v-if="info.invoice_list && info.invoice_list.length">
      <div class="invoiceDetail-title">发票详细</div>
      <div class="invoiceDetail-info-re" v-for="(item, index) in info.invoice_list" :key="index">
        <div class="invoiceDetail-con-list">
          <div class="invoiceDetail-con-list-tit">发票代码：</div>
          <div class="invoiceDetail-con-list-val">{{item.mii_invoice_code}}</div>
        </div>
        <div class="invoiceDetail-con-list">
          <div class="invoiceDetail-con-list-tit">发票号：</div>
          <div class="invoiceDetail-con-list-val">{{item.mii_invoice_number}}</div>
        </div>
        <div class="invoiceDetail-con-list">
          <div class="invoiceDetail-con-list-tit">状态：</div>
          <div style="display: flex;justify-content: space-between;flex: 1">
            <div class="invoiceDetail-con-list-val invoiceDetail-tip">{{isInvoiceState(item.mii_status)}}
            </div>
            <!--            <div-->
            <!--              v-if="item.mii_status === 2"-->
            <!--              class="buttom buttomred"-->
            <!--              @click="onDownload(item)"-->
            <!--            >查看发票-->
            <!--            </div>-->
            <div style="display: flex" v-if="item.mii_status === 2">
              <a class="buttom" target="_blank" :href="item.mii_url">查看发票</a>
              <div class="buttom buttomred" @click="onShowEmail(item)">发送邮箱</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!--    <div v-else class="invoiceDetail-tip">提示：订单完成后开票</div>-->

    <confirm v-model="isEmail"
             title="发送邮箱"
             theme="android"
             @on-cancel="isEmail = false"
             :close-on-confirm="false"
             @on-confirm="onConfirmEmail">
      <input class="invoice-input" placeholder="请输入接收发票的邮箱" v-model="emailParams.email" @focusout="inputBlur" @focusin="inputFocus">
    </confirm>

  </div>
</template>

<script>
  import Enum from '@/config/enum'
  import Me from '@/dll/me'

  export default {
    name: 'invoiceDetail',
    data () {
      return {
        ordersState: Enum.MALL_ORDERS_STATE,
        invoiceDetail: JSON.parse(this.$route.query.invoiceDetail),
        orderList: [], // 订单信息
        invoiceList: [], // 发票信息
        perList: [], // 收票信息
        info: {},

        // 发送到邮箱
        emailParams: {
          email: '',
          request_order_sn: ''
        },
        isEmail: false,
        email_reg: /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})(\.[a-zA-Z]{2,4})?$/
      }
    },
    created () {
      this.triggerInvoice()
      this.$nextTick(function () {
        this.orderList = [
          { name: '订单状态', value: this.invoiceDetail.state_desc },
          { name: '订单编号', value: this.invoiceDetail.sub_order_id },
          { name: '下单时间', value: this.invoiceDetail.created_date }
        ]
      })
    },
    computed: {
      // 开票状态
      invoiceStatus () {
        let status = parseFloat(this.info.invoice_status)
        if (status === 1) {
          return '开票成功'
        } else if (status === 0) {
          return '待开票'
        } else if (status === 2) {
          return '已冲红'
        } else {
          return '开票成功'
        }
      },

      // 判断是否是增值发票
      isIncrement () {
        return this.info.invoice_info && parseFloat(this.info.invoice_info.type) === 2
      },

      // 判断是否是个人发票
      isPersonal () {
        return this.info.invoice_info && parseFloat(this.info.invoice_info.type) === 0
      },

      // 判断是否是单位发票
      isUnit () {
        return this.info.invoice_info && parseFloat(this.info.invoice_info.type) === 1
      },

      // 判断发票
      invoiceText () {
        if (this.isIncrement) {
          return '增值税专用发票'
        } else {
          return '普通发票'
        }
      },

      // 发票状态
      isInvoiceState () {
        return (status) => {
          let _status = parseFloat(status)
          if (_status === 1 || _status === 21) {
            return '开票中'
          }
          if (_status === 22) {
            return '开票失败'
          }
          if (_status === 2) {
            return '开票成功'
          }
          if (_status === 3 || _status === 51) {
            return '发票已作废'
          }
          if (_status === 31) {
            return '发票作废中'
          }
          if (_status === 20) {
            return '未开票'
          }
          if (_status === 50) {
            return '已冲红'
          }
        }
      },

      // 发票内容
      isInvoiceContent () {
        let state
        if (this.info.invoice_info.vat) {
          state = this.info.invoice_info.vat.content
        }
        if (this.info.invoice_info.general) {
          state = this.info.invoice_info.general.content
        }
        if (this.info.invoice_info.personal) {
          state = this.info.invoice_info.personal.content
        }
        if (parseFloat(state) === 1) {
          return '商品明细'
        } else {
          return '商品类型'
        }
      },

      // 判断订单进度
      orderActive () {
        if (this.ordersState['待发货'] === this.invoiceDetail.order_state) {
          return 1 // 待发货
        } else if (this.ordersState['已完成'] === this.invoiceDetail.order_state) {
          if (this.info.invoice_list && this.info.invoice_list.length !== 0) {
            return 3 // 发票开成功
          } else {
            return 2 // 交易完成
          }
        }
        return 0
      }
    },
    methods: {
      // 触发开票
      async triggerInvoice () {
        this.$vux.loading.show({
          text: '请稍后'
        })
        await Me.askInvoice({ order_sn: this.invoiceDetail.order_sn })
        this.getInvoiceInfo()
        this.$vux.loading.hide()
      },

      // 获取发票详情
      async getInvoiceInfo () {
        this.$vux.loading.show({
          text: '请稍后'
        })
        let res = await Me.getInvoiceInfo({ order_sn: this.invoiceDetail.order_sn })
        this.$vux.loading.hide()
        if (res.code == 0) {
          this.info = res.data
          if (this.isPersonal) {
            this.invoiceList = [
              // { name: '发票状态', value: this.isInvoiceState.text },
              { name: '发票内容', value: this.isInvoiceContent },
              { name: '发票抬头', value: `个人(${this.info.invoice_info.personal.title})` },
              { name: '发票类型', value: this.invoiceText, isRed: true }
            ]

            this.perList = [
              { name: '联系电话', value: this.info.invoice_info.personal.phone }
            ]
          }
          if (this.isUnit) {
            this.perList = [
              { name: '联系电话', value: this.info.invoice_info.general.phone }
            ]

            this.invoiceList = [
              { name: '发票内容', value: this.isInvoiceContent },
              { name: '发票抬头', value: `企业(${this.info.invoice_info.general.company})` },
              { name: '发票类型', value: this.invoiceText, isRed: true }
            ]
          }
          if (this.isIncrement) {
            this.invoiceList = [
              // { name: '发票状态', value: this.isInvoiceState.text },
              { name: '发票内容', value: this.isInvoiceContent },
              { name: '发票抬头', value: `企业(${this.info.invoice_info.vat.company})` },
              { name: '发票类型', value: this.invoiceText, isRed: true }
              // { name: '纳税人识别号', value: this.info.invoice_info.general.code },
              // { name: '注册地址', value: this.info.invoice_info.general.reg_address },
              // { name: '注册电话', value: this.info.invoice_info.general.reg_phone },
              // { name: '银行账号', value: this.info.invoice_info.general.reg_bank_account },
            ]
            this.perList = [
              { name: '联系电话', value: this.info.invoice_info.vat.phone },
              { name: '收票人', value: this.info.invoice_info.vat.name },
              { name: '联系地址', value: this.info.invoice_info.vat.address }
            ]
          }
        } else {
          this.$vux.alert.show({
            title: '提示',
            content: res.msg
          })
        }
      },

      // 发票下载
      async onDownload (item) {
        this.$vux.loading.show({
          text: '请稍后'
        })
        let data = Me.downloadInvoice({ request_order_sn: item.mii_request_order_sn })
        const req = new XMLHttpRequest()
        req.open('GET', data)
        req.responseType = 'blob'
        req.setRequestHeader('Content-Type', 'application/json')
        req.onload = () => {
          this.$vux.loading.hide()
          const blob = new Blob([req.response])
          const blobUrl = window.URL.createObjectURL(blob)
          this.saveFile(blobUrl)
        }
        req.send()
      },
      saveFile (blobUrl) {
        const a = document.createElement('a')
        a.style.display = 'none'
        a.download = '发票.pdf'
        a.href = blobUrl
        a.click()
      },

      // 显示发票邮箱弹框
      onShowEmail (item) {
        this.emailParams.request_order_sn = item.mii_request_order_sn
        this.isEmail = true
      },

      // 发送到邮箱
      async onConfirmEmail () {
        if (!this.email_reg.test(this.emailParams.email)) {
          this.$vux.toast.text('请输入正确的邮箱地址')
        } else {
          this.$vux.loading.show({
            text: '请稍后'
          })
          let res = await Me.sendEmail(this.emailParams)
          this.$vux.loading.hide()
          if (res.code == 0) {
            this.isEmail = false
            this.$vux.alert.show({
              title: '提示',
              content: '已发送'
            })
          } else {
            this.$vux.alert.show({
              title: '提示',
              content: res.msg
            })
          }
        }
      }
    }
  }
</script>

<style lang="less">
  .invoiceDetail {
    .invoiceDetail-title {
      font-weight: bold;
      padding: 4px 0;
    }

    .invoiceDetail-con {
      background: #fff;
      padding: 10px;
      margin: 10px;
      border-radius: 5px;
      font-size: 14px;

      .invoiceDetail-con-list {
        display: flex;
        padding: 4px 0;

        .invoiceDetail-con-list-tit {
          flex-shrink: 0;
          width: 70px;
          text-align: right;
        }
      }
    }

    .invoiceDetail-info {
      padding: 0;

      .invoiceDetail-title {
        padding: 10px 0 4px 10px;
      }

      .invoiceDetail-info-re {
        border: 1px solid #fbf8f7;
        padding: 10px;
      }
    }

    .buttom {
      height: 28px;
      display: block;
      box-sizing: border-box;
      width: 64px;
      font-size: 12px;
      color: #46241e;
      line-height: 26px;
      text-align: center;
      border: 1px solid #d4d4d4;
      margin-left: 5px;
    }

    .buttom.buttomred {
      color: #fff;
      border-color: #b0290f;
      background-color: #b0290f;
    }

    .invoiceDetail-tip {
      color: #b0290f;
    }
  }

  .invoice-input {
    width: 100%;
    padding: 0 10px;
    box-sizing: border-box;
  }

  /deep/ .weui-dialog__bd {
    padding-bottom: 10px !important;
  }
</style>
